import * as PIXI from 'pixi.js'
import { PixiComponent } from '@inlet/react-pixi'

function onDragStart(callback, scale) {
  return (event) => {
    const position = event.data.getLocalPosition(this)
    console.log('click', position.x, position.y)
    callback(position.x / scale, position.y / scale)
  }
}

export default PixiComponent('Tough_layer', {
  create: () => new PIXI.Container(),
  didMount: () => {},
  willUnmount: () => { },
  applyProps: (instance, oldProps, newProps) => {
    const { scale, onClick, image } = newProps
    if (onClick) {
      instance.x = -0.5 * image.get('width') * scale
      instance.y = -0.5 * image.get('height') * scale
      instance.interactive = true
      instance.hitArea = new PIXI.Rectangle(0, 0, image.get('width') * scale, image.get('height') * scale)
      instance.removeAllListeners(['pointerdown'])
      instance.on('pointerdown', onDragStart(onClick, scale))
    } else {
      instance.interactive = false
    }
  },
})
